package cn.chair.controller.admin;

import cn.chair.dao.ChairDao;
import cn.chair.dao.MerchantDao;
import cn.chair.dao.RegionDao;
import cn.chair.entity.Chair;
import cn.chair.entity.Merchant;
import cn.chair.entity.Region;
import cn.chair.model.Result;
import cn.chair.model.admin.MerchantListResp;
import cn.chair.model.admin.MerchantReq;
import cn.chair.model.admin.MerchantResp;
import cn.chair.model.admin.RegionResp;
import cn.chair.util.SmallUtil;
import com.cfilmcloud.framework.privilege.api.model.LevelDetails;
import com.cfilmcloud.framework.privilege.api.model.UserProfile;
import life.innovation.builder.SqlBuilder;
import life.innovation.exception.DataReadException;
import life.innovation.exception.DataWriteException;
import life.innovation.exception.ResourceNotFoundException;
import life.innovation.exception.UnauthorizedException;
import life.innovation.model.PageList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@RequestMapping(value="merchant")
@RestController
public class MerchantController{
    private static final Logger log = LoggerFactory.getLogger("appLogger");
    private static final Logger elog = LoggerFactory.getLogger("errorLogger");
    @Autowired
    @Lazy
    private MerchantDao merchantDao;
    @Autowired
    @Lazy
    private RegionDao regionDao;
    @Autowired
    @Lazy
    private ChairDao chairDao;

    /**
     * 添加影院
     * @param request
     * @param req
     * @throws DataWriteException
     * @throws UnauthorizedException
     */
    @PostMapping(value = "addMerchant")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @Transactional
    public void add(HttpServletRequest request,@RequestBody MerchantReq req) throws DataWriteException, UnauthorizedException {


        Merchant merchant = new Merchant();
        merchant.setOrgId(1);
        merchant.setName(req.getName());
        merchant.setCreatedAt(new Date());
        merchant.setStatus(req.getStatus());
        merchant.setLongitude(req.getLongitude());
        merchant.setLatitude(req.getLatitude());
        merchant.setLinkMan(req.getLinkMan());
        merchant.setPhone(req.getPhone());
        merchant.setAddress(req.getAddress());
        merchant.setRegionId(req.getRegionId());
        merchant.setPackageGroupId(0);
        merchant.setMerchant_config_id(0);

        merchantDao.insert(merchant);

        insertRegion(req.getRegionId());


    }

    /**
     * 获取单条影院信息
     * @param id
     * @return
     * @throws ResourceNotFoundException
     */
    @GetMapping(value="{id}")
    public Merchant selectMerchant(@PathVariable int id) throws ResourceNotFoundException {
       Merchant merchant = merchantDao.findOne(SqlBuilder.init().where("id",id));
       if(merchant == null){
           throw new ResourceNotFoundException("error.merchant.missing");
       }
       return merchant;
    }

    @PostMapping(value="updateMerchant")
    @Transactional
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void updateMerchant(HttpServletRequest request,@RequestBody MerchantReq req ) throws DataWriteException, ResourceNotFoundException, UnauthorizedException {

        Merchant merchant = merchantDao.findOne(SqlBuilder.init().where("id",req.getId()));
        if(merchant == null){
            throw new ResourceNotFoundException("error.merchant.missing");
        }

            merchant.setName(req.getName());
            merchant.setRegionId(req.getRegionId());
            merchant.setStatus(req.getStatus());
            merchant.setLongitude(req.getLongitude());
            merchant.setLatitude(req.getLatitude());
            merchant.setLinkMan(req.getLinkMan());
            merchant.setPhone(req.getPhone());
            merchant.setAddress(req.getAddress());

            merchantDao.update(merchant);

            insertRegion(req.getRegionId());

    }
    @GetMapping(value="getMerchants")
    public MerchantListResp find(@RequestParam(required = false) Integer regionId,
                                 @RequestParam(required = false) Integer merId,
                                 @RequestParam(required = false) String merName,
                                 @RequestParam(required = false) Integer status,
                                 @RequestParam(required = false,defaultValue = "1")int page,
                                 @RequestParam(required = false,defaultValue = "20")int countPerPage) throws DataReadException {

        MerchantListResp resp = new MerchantListResp();

        PageList<MerchantListResp.MerchantList> list = merchantDao.getMerchantList(regionId,merId,merName,status,page,countPerPage);
        List<MerchantListResp.MerchantList> merList =  list.getList();
        for(MerchantListResp.MerchantList merchantList:merList){
            List<Chair> chairs = chairDao.find(SqlBuilder.init().where("merchant_id",merchantList.getMerId()));
            if(chairs!=null&&chairs.size()>0){
                merchantList.setChairCount(chairs.size());
            }else{
                merchantList.setChairCount(0);
            }

            List<Chair> broken = chairDao.find(SqlBuilder.init().where("merchant_id", merchantList.getMerId()).where("run_status", 0));
            if (broken != null && broken.size() > 0) {
                merchantList.setBrokenCount(broken.size());
            } else {
                merchantList.setBrokenCount(0);
            }
        };

        resp.setPagination(list.getPagination());
        resp.setList(merList);
        return resp;
    }



 public void insertRegion(int regionId) throws DataWriteException {
     List<RegionResp> list = RegionController.getRegions();

     for(RegionResp resp:list){
         if(resp.getCode().equals(String.valueOf(regionId))){
             Region regionCity = regionDao.findOne(SqlBuilder.init().where("org_id",regionId));
             if(regionCity == null){
                 Region region = new Region();
                 region.setOrgId(regionId);
                 region.setName(resp.getName());
                 regionDao.insert(region);

             }
             break;
         }

     }

 }

    /**
     * 修改价格组
     *
     * @param id
     * @param groupId
     */
    @PutMapping(value="{id}")
  public Map<String,Object> addPackageGroup(@PathVariable int id, @RequestParam int groupId ) throws DataWriteException {
        Merchant merchant = merchantDao.findOne(SqlBuilder.init().where("id",id));
        if(merchant != null){
            merchant.setPackageGroupId(groupId);
        }
        merchantDao.update(merchant);
        Map<String,Object> map = new HashMap<>();
        map.put("success",true);
        return map;
    }


@PostMapping(value="getMerchants")
 public List<MerchantResp> get(UserProfile userProfile) throws DataReadException {
    LevelDetails levelDetails = userProfile.getLevelDetails();

    List<Integer> storeId = null;
    if(!SmallUtil.isEmpty(levelDetails.getStoreId())){
        List<String> stores = Arrays.asList(levelDetails.getStoreId().split(","));
        storeId = stores.stream().map(Integer::parseInt).collect(Collectors.toList());
    }


    List<MerchantResp> resps = merchantDao.getList(storeId);


        return resps;
 }


}
